package com.cskaoyan.mall.utils;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUploadUtils {
    public static Map<String, String> getFileUploadOfMap(HttpServletRequest req){

        DiskFileItemFactory factory = new DiskFileItemFactory();

        ServletContext servletContext = req.getServletContext();

        File tempDirectory = (File) servletContext.getAttribute("javax.servlet.context.tempdir");

        factory.setRepository(tempDirectory);

        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        Map<String,String> map= new HashMap<>();
        try {
            List<FileItem> fileItems = upload.parseRequest(req);

            for (FileItem fileItem : fileItems) {
                if(fileItem.isFormField()){
                    processFormField(fileItem,map);
                }else {

                    processUploadedFile(fileItem,map,req);
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
//处理文件上传
    private static void processUploadedFile(FileItem fileItem, Map<String,String> map, HttpServletRequest req) throws Exception {
        String fieldName = fileItem.getFieldName();
        String fileName = fileItem.getName();
        String relativePath ="image/" + fileName;
        String realPath = req.getServletContext().getRealPath(relativePath);
        File file = new File(realPath);
        if(!file.getParentFile().exists()){
            file.getParentFile().mkdirs();
        }
        map.put(fieldName,relativePath);
        fileItem.write(new File(realPath));
    }

    private static void processFormField(FileItem fileItem, Map<String,String> map) {
        String fieldName = fileItem.getFieldName();
        String name = null;
        try {
            name = fileItem.getString("utf-8");
            map.put(fieldName,name);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        System.out.println(fieldName+":"+name);
    }

}
